package com.imooc.controller;

import com.imooc.vo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @author xiaoming
 * @version 1.0
 * @date 2019-04-13 9:58
 **/
@Controller
public class UserController {

    @RequestMapping(value = "/subLogin", method = RequestMethod.POST,
            produces = "application/json;charset=utf-8")
    @ResponseBody
    public String subLogin(User user){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
//            自动登录
            token.setRememberMe(user.isRememberMe());
            subject.login(token);
        } catch (AuthenticationException e) {
            return e.getMessage();
        }

        // 授权
        if (subject.hasRole("admin")) {
            return "登录成功有admin权限";
        }
        return "登录成功, 没有admin权限";
    }

    /**
     * 注解授权
     * @return
     */
    @RequiresRoles("admin") // admin角色才能访问
    //@RequiresPermissions()
    @RequestMapping(value = "/testRole" ,method = RequestMethod.GET)
    @ResponseBody
    public String testRole() {

        return "testRole success";
    }

    @RequiresRoles("admin1") // admin1 角色才能访问
    @RequestMapping(value = "/testRole1" ,method = RequestMethod.GET)
    @ResponseBody
    public String testRole1() {

        return "testRole1 success";
    }

    // 测试Shio 过滤器
    //@RequiresRoles("admin1") // admin1 角色才能访问
    @RequestMapping(value = "/testRole2" ,method = RequestMethod.GET)
    @ResponseBody
    public String testRole2() {

        return "testRole2 success (Shiro Filter: admin)";
    }

    @RequestMapping(value = "/testRole3" ,method = RequestMethod.GET)
    @ResponseBody
    public String testRole3() {

        return "testRole3 success (Shiro Filter: admin , admin1)";
    }

    // 测试 自定义Shiro Filter
    @RequestMapping(value = "/testRole4" ,method = RequestMethod.GET)
    @ResponseBody
    public String testRole4() {

        return "testRole4 success (Shiro Filter: admin or admin1)";
    }

}
